package com.ohuang.util_a

import android.util.Log
import java.lang.reflect.Proxy
import java.util.Arrays

inline fun <reified T> createProxy(): T {
    val proxy = Proxy.newProxyInstance(
        T::class.java.classLoader,
        arrayOf(T::class.java)
    ) { proxy, method, args ->
        return@newProxyInstance null
    } as T
    return proxy
}

inline fun <reified T> createProxy(obj: T): T {
    val proxy = Proxy.newProxyInstance(
        T::class.java.classLoader,
        arrayOf(T::class.java)
    ) { proxy, method, args ->

        if (obj == null) {
            return@newProxyInstance null
        }
        method.invoke(obj, *(args ?: emptyArray())) // 关键：调用target而不是proxy

    } as T
    return proxy
}


inline fun <reified T> createLogProxy(obj: T? = null, tag: String): T {
    val proxy = Proxy.newProxyInstance(
        T::class.java.classLoader,
        arrayOf(T::class.java)
    ) { proxy, method, args ->
        Log.d(tag, "${method.name}: ${args.contentToString()}")
        if (obj == null) {
            return@newProxyInstance null
        }
        method.invoke(obj, *(args ?: emptyArray())) // 关键：调用target而不是proxy
    } as T

    return proxy
}